package fr.sedoo.metadata.client.ui.widget.table.format;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.commons.client.widget.ConfirmCallBack;
import fr.sedoo.commons.client.widget.dialog.DialogBoxContent;
import fr.sedoo.metadata.client.ui.editablechosen.MultipleValueTextBox;
import fr.sedoo.metadata.shared.domain.dto.FormatDTO;

public class FormatDialogBoxContent extends Composite implements DialogBoxContent {

	private static FormatDialogBoxContentUiBinder uiBinder = GWT.create(FormatDialogBoxContentUiBinder.class);

	interface FormatDialogBoxContentUiBinder extends UiBinder<Widget, FormatDialogBoxContent> {
	}

	@UiField
	TextBox name;

	@UiField
	MultipleValueTextBox versions;

	@UiField
	Button ok;

	@UiField
	Button cancel;

	Long id;

	private DialogBox dialog;

	private FormatDTO resultValue;

	private ConfirmCallBack confirmCallback;

	public FormatDialogBoxContent(ConfirmCallBack confirmCallback) {
		initWidget(uiBinder.createAndBindUi(this));
		this.confirmCallback = confirmCallback;
		versions.setSize("600px", "50px");
	}

	@UiHandler("cancel")
	void onCancelClicked(ClickEvent event) {
		if (dialog != null) {
			dialog.hide();
		}
	}

	@UiHandler("ok")
	void onOkClicked(ClickEvent event) {

		if (dialog != null) {
			dialog.hide();
			resultValue = flush();
			confirmCallback.confirm(true);
		}
	}

	private FormatDTO flush() {
		FormatDTO aux = new FormatDTO();
		aux.setName(name.getText().trim());
		aux.setVersions(versions.getValues());
		aux.setId(id);

		return aux;
	}

	public void setDialogBox(DialogBox dialog) {
		this.dialog = dialog;
	}

	public FormatDTO getResultValue() {
		return resultValue;
	}

	public void setResultValue(FormatDTO resultValue) {
		this.resultValue = resultValue;
	}

	public void edit(FormatDTO item) {
		if (item != null) {
			name.setText(StringUtil.trimToEmpty(item.getName()));
			versions.setValues(item.getVersions());
			id = item.getId();
		}
	}

	@Override
	public String getPreferredHeight() {
		return "200px";
	}

}
